package com.cheer.ba.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.Type;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.presenter.impl.AskQuestPresenter;
import com.cheer.ba.presenter.impl.LoginPresenter;
import com.cheer.ba.service.BackGroundService;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.NetUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import io.card.payment.CardIOActivity;
import io.card.payment.CreditCard;

/**
 * Created by Hq on 2017/7/31.
 * 添加我的银行卡
 */
public class AddMyBankAty extends BaseCommAty {

    @BindView(R.id.id_bank_phone_edit)
    EditText mEditPhone;
    private String mSavePhone;

    @BindView(R.id.id_bank_code_edit)
    EditText mEditCode;
    private String mSaveCode;
    @BindView(R.id.id_send_phone_btn)
    Button mBtnSendCode;

    @BindView(R.id.id_bank_name_edit)
    EditText mEditName;
    private String mSaveName;

    @BindView(R.id.id_bank_num_edit)
    EditText mEditBankNum;
    private String mSaveBankNum;

    @BindView(R.id.id_bank_address_edit)
    EditText mEditBankAddress;
    private String mSaveBankAddress;

    private static final char kongge = ' ';

    private LoginPresenter mLoginPresenter;

    /**
     * 倒计时类
     */
    private MyCount mc;


    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_add_bank, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new AskQuestPresenter();

        mLoginPresenter = new LoginPresenter();
        mLoginPresenter.attachView(this);
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText("添加银行卡");
        if (BackGroundService.time_code != 0) {
            startCount(BackGroundService.time_code);
        }
        mEditBankNum.addTextChangedListener(new TextWatcher() {
            // 改变之前text长度
            int beforeTextLength = 0;
            // 改变之前的文字
            private CharSequence beforeChar;
            // 改变之后text长度
            int onTextLength = 0;
            // 是否改变空格或光标
            boolean isChanged = false;
            // 记录光标的位置
            int location = 0;
            private char[] tempChar;
            private StringBuffer buffer = new StringBuffer();
            // 已有空格数量
            int konggeNumberB = 0;

            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                onTextLength = s.length();
                buffer.append(s.toString());
                if (onTextLength == beforeTextLength || onTextLength <= 3
                        || isChanged) {
                    isChanged = false;
                    return;
                }
                isChanged = true;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                                          int arg3) {
                beforeTextLength = s.length();
                if (buffer.length() > 0) {
                    buffer.delete(0, buffer.length());
                }
                konggeNumberB = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == ' ') {
                        konggeNumberB++;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isChanged) {
                    location = mEditBankNum.getSelectionEnd();
                    int index = 0;
                    while (index < buffer.length()) {
                        if (buffer.charAt(index) == kongge) {
                            buffer.deleteCharAt(index);
                        } else {
                            index++;
                        }
                    }
                    index = 0;
                    int konggeNumberC = 0;
                    while (index < buffer.length()) {
                        if ((index - 4) % 5 == 0) {
                            buffer.insert(index, kongge);
                            konggeNumberC++;
                        }
                        index++;
                    }

                    if (konggeNumberC > konggeNumberB) {
                        location += (konggeNumberC - konggeNumberB);
                    }

                    tempChar = new char[buffer.length()];
                    buffer.getChars(0, buffer.length(), tempChar, 0);
                    String str = buffer.toString();
                    if (location > str.length()) {
                        location = str.length();
                    } else if (location < 0) {
                        location = 0;
                    }
                    mEditBankNum.setText(str);
                    Editable etable = mEditBankNum.getText();
                    Selection.setSelection(etable, location);
                    isChanged = false;
                }
            }
        });
    }

    /**
     * 获得参数
     */
    public void getData() {
        mSavePhone = mEditPhone.getText().toString().trim();
        mSaveCode = mEditCode.getText().toString().trim();
        mSaveName = mEditName.getText().toString().trim();
        mSaveBankNum = mEditBankNum.getText().toString().replaceAll(" ", "").trim();
        mSaveBankAddress = mEditBankAddress.getText().toString().trim();
    }

    @OnClick({R.id.id_send_phone_btn, R.id.id_bank_remind_rela, R.id.id_bank_camer_rela, R.id.id_bank_submit})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_send_phone_btn:
                //发送验证码
                getData();
                if (!StringUtils.isMobile(mSavePhone)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.phone_error));
                    return;
                }
                if (!NetUtils.isNetworkConnected(aty)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_net_work));
                } else {
                    BackGroundService.countDownCode(Constants.COUNTDOWN * 1000);
                    startCount(Constants.COUNTDOWN * 1000);
                    mLoginPresenter.getVeriCode(mSavePhone, Type.VERIFY_BANK, Session.getUserId());
                }
                break;
            case R.id.id_bank_remind_rela:
                //提示

                break;
            case R.id.id_bank_camer_rela:
                //拍照
                checkPermissCamer();
                break;
            case R.id.id_bank_submit:
                //提交验证
                getData();
                if (!StringUtils.isMobile(mSavePhone)) {
                    SVProgressHUD.showInfoWithStatus(aty, "请输入正确的手机号");
                } else {
                    if (StringUtils.isEmpty(mSaveCode)) {
                        SVProgressHUD.showInfoWithStatus(aty, "请输入验证码");
                    } else {
                        if (StringUtils.isEmpty(mSaveName)) {
                            SVProgressHUD.showInfoWithStatus(aty, "请输入姓名");
                        } else {
                            if (StringUtils.isEmpty(mSaveBankNum)) {
                                SVProgressHUD.showInfoWithStatus(aty, "请输入银行卡号");
                            } else {
                                if (StringUtils.isEmpty(mSaveBankAddress)) {
                                    SVProgressHUD.showInfoWithStatus(aty, "请输入开户行地址");
                                } else {
                                    ((AskQuestPresenter) presenter).addMyBank(true, mSavePhone, mSaveBankNum, mSaveName, mSaveCode, mSaveBankAddress);
                                }
                            }
                        }
                    }
                }
                break;
        }
    }

    /**
     * 处理接口返回数据
     *
     * @author HQ
     * created at 2017/3/8 0008 11:30
     */
    @Override
    public void handlerByPage(int flag1, int flag2, String string) {
        if (flag1 == CodeStatus.Gegeneral.DATA_SUCCESS_FULL) {
            //获取短信验证码成功

        } else if (flag1 == CodeStatus.Gegeneral.ERROR_DATA) {
            //获取短信验证码失败
            SVProgressHUD.showInfoWithStatus(aty, string);
            mBtnSendCode.setText(getString(R.string.send_check_code));
            mBtnSendCode.setEnabled(true);
            if (mc != null) {
                mc.cancel();
            }
            if (null != BackGroundService.countCode) {
                BackGroundService.countCode.cancel();
            }
            BackGroundService.time_code = 0;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.ADD_MY_BANKS)) {
                SVProgressHUD.showSuccessWithStatus(aty, "添加银行卡成功");
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.ADD_MY_BANKS;
                EventBus.getDefault().post(event);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);

            }
        }
    }

    /**
     * 启动倒计时
     */
    private void startCount(long time) {
        mBtnSendCode.setEnabled(false);
        if (null != mc) {
            mc.cancel();
            mc = null;
        }
        mc = new MyCount(time, 1000);
        mc.start();
    }

    /**
     * 倒计时类
     */
    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnSendCode.setText(millisUntilFinished / 1000
                    + getString(R.string.regist_second));
        }

        @Override
        public void onFinish() {
            mBtnSendCode.setText(getString(R.string.send_check_code));
            mBtnSendCode.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mc) {
            mc.cancel();
        }
    }

    /**
     * 检测用户是否开启权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            toPhotoGraph();
        }
    }

    /**
     * 银行卡获取
     */
    private void toPhotoGraph() {
        Intent scanIntent = new Intent(this, CardIOActivity.class);

        // customize these values to suit your needs.
        scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default: false
        scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default: false
        scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default: false

        // MY_SCAN_REQUEST_CODE is arbitrary and is only used within this activity.
        startActivityForResult(scanIntent, IntentCode.ScanBank.SCANBANK_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentCode.ScanBank.SCANBANK_REQUEST) {
            String resultDisplayStr;
            if (data != null && data.hasExtra(CardIOActivity.EXTRA_SCAN_RESULT)) {
                CreditCard scanResult = data.getParcelableExtra(CardIOActivity.EXTRA_SCAN_RESULT);

                // Never log a raw card number. Avoid displaying it, but if necessary use getFormattedCardNumber()
                resultDisplayStr = "Card Number: " + scanResult.getRedactedCardNumber() + "\n";

                LogUtils.LogD("银行卡", "银行卡账号是：" + scanResult.cardNumber);
                mEditBankNum.setText(scanResult.cardNumber);

                if (scanResult.isExpiryValid()) {
                    resultDisplayStr += "Expiration Date: " + scanResult.expiryMonth + "/" + scanResult.expiryYear + "\n";
                }

                if (scanResult.cvv != null) {
                    // Never log or display a CVV
                    resultDisplayStr += "CVV has " + scanResult.cvv.length() + " digits.\n";
                }

                if (scanResult.postalCode != null) {
                    resultDisplayStr += "Postal Code: " + scanResult.postalCode + "\n";
                }
                LogUtils.LogD("扫描", resultDisplayStr);
            } else {
                ToastUtil.showToast("扫描取消");
            }
        }
    }

}
